import Vue from 'vue'
import axios from 'axios'
import {getStore} from './storage'

let http = axios.create({
    // baseURL: '/api',
    baseURL: `${getStore('localhost')}`,
});

http.interceptors.request.use(config=>{
    config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    let token = getStore('token');
    if(token){
        config.headers.common['token'] = token;
        config.headers.common['Cache-Control'] = 'no-cache';
    }
    return config
},error=>{
    Vue.prototype.$message.error(error)
    return Promise.reject(error)
})

http.interceptors.response.use(
    response => {
        if(response.status === 200){
            const { returnCode, returnMessage, errorMessage } = response.data;
            if(returnCode == 1){
                Vue.prototype.$message.error(returnMessage, errorMessage);
                return Promise.reject(response)
            }
            return Promise.resolve(response)
        }else{
            return Promise.reject(response)
        }
    },
    error => {
        const { status } = error.response;
        const {config} = error.response
        let url = config.url.indexOf('?') != -1 ? config.url.split('?')[0] : config.url;
        if(status){
            switch(status){
                case 401:
                    if(getStore('localhost')){
                        setTimeout(()=>{
                            parent.location.href = `${getStore('localhost')}`;
                        },1000)
                    }
                    break;
                case 404:
                    Vue.prototype.$message.error(`未找到 ${url} 的资源,请重新刷新或联系管理员`);
                    break;
                default:
                    break;
            }
            if(error.response.data.returnMessage) Vue.prototype.$message.error(error.response.data.returnMessage)
            return Promise.reject(error.response)
        }
    }
  )

export default http;